/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tools.adtui.swing

import com.intellij.openapi.util.IconLoader
import com.intellij.ui.IconManager
import org.junit.rules.ExternalResource

/**
 * Enables icon loading in a headless test environment. Use as a class rule.
 *
 * Please notice that since icons are cached and not reloaded for each test, loading of icons
 * has to be enabled before the first test in the suite that may trigger icon loading. It is
 * therefore recommended to add
 * ```
 *   static {
 *     IconLoaderRule.enableIconLoading();
 *   }
 * ```
 * to the test suite class in addition to using the [IconLoaderRule] in each test that depends
 * on realistic icon appearance.
 */
class IconLoaderRule : ExternalResource() {
  private var wasEnabled = false

  override fun before() {
    val oldIconManagerClass = IconManager.getInstance().javaClass
    enableIconLoading()
    wasEnabled = IconManager.getInstance().javaClass == oldIconManagerClass
  }

  override fun after() {
    if (!wasEnabled) {
      disableIconLoading()
    }
  }

  companion object {
    @JvmStatic
    fun enableIconLoading() {
      IconManager.activate(null)
      IconLoader.activate()
    }

    @JvmStatic
    fun disableIconLoading() {
      IconLoader.deactivate()
      IconManager.deactivate()
    }
  }
}
